class UserController < ApplicationController
  
  include ApplicationHelper

  before_filter :protect, :except => [:login, :register]
  protect_from_forgery :secret => '10000'
  
  def index
    @title = "欢迎您的到来，这里是用户体验中心"
  end

  def register
    @title = "注册"
    if param_posted?(:user)
      @user = User.new(params[:user])
      if @user.save
        @user.login!(session)
        flash[:notice] = "用户#{@user.screen_name}被成功创建"
        redirect_to_forwarding_url
      else
        @user.clear_password!
      end
    end
  end

  def login
    @title = "成为Oasis的成员"
    if param_posted?(:user)
      @user = User.new(params[:user])
      user = User.find_by_screen_name_and_password(@user.screen_name, @user.password)
      if user
        user.login!(session)
        flash[:notioc] = "用户#{user.screen_name}登陆了"
        redirect_to_forwarding_url
      else
        # 不要再把用户的密码显示在页面上
        @user.clear_password!
        flash[:notice] = "非法的用户名或者密码"
      end
    end
  end

  def logout
    User.logout!(session)
    flash[:notice] = "已经安全退出"
    redirect_to :action => "index", :controller => "site"
  end

  private

  # 防止页面在非授权的情况下被访问
  def protect
    unless logged_in?
      session[:protected_page] = request.request_uri
      flash[:notice] = "你需要先登陆"
      redirect_to :action => "login"
    end
  end

  # 若给定标号所对应的参数被post则返回true
  def param_posted?(symbol)
    request.post? and params[symbol]
  end
  
  # 转向之前请求的页面（如果该页面存在的话）
  def redirect_to_forwarding_url
    if(redirect_url = session[:protected_page])
          session[:protected_page]= nil
          redirect_to redirect_url
        else
          redirect_to :action =>"index"
        end
  end
end
